package com.lmk.mkcc.mq.listener;

import com.alibaba.fastjson.JSON;
import com.lmk.mkcc.domain.CourseOrder;
import com.lmk.mkcc.dto.PayDto;
import com.lmk.mkcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup ="corse-order-sw-producer-group")
public class CourseOrderRocketMqListener implements RocketMQLocalTransactionListener {// mq执行本地事务
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            log.info("开始执行本地事务");
            if (o==null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            // 将obj类型的o转化为对象
            CourseOrder courseOrder = JSON.parseObject(o.toString(), CourseOrder.class);
            // 根据订单号查询订单号是否存在
            CourseOrder courseOrder1 = courseOrderService.getByorderNo(courseOrder.getOrderNo());
            if (courseOrder1!=null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            courseOrderService.addCourseOrderAndCourseOrderItem(courseOrder);
            log.info("本地事务执行结束");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("事务出现异常");
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            // 先将集合转化为byte数组
            byte[] bytes = (byte[])message.getPayload();
            String s = new String(bytes, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(s, PayDto.class);
            if (payDto == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder byorderNo = courseOrderService.getByorderNo(payDto.getOrderNo());
            if (byorderNo == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("事务出现异常");
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }
}
